<?php
declare (strict_types = 1);
namespace app\index\model\user;

use app\index\model\charge\ChargePile;
use app\index\model\charge\ChargingStation;
use think\Model;

/**
 * @mixin \think\Model
 */
class UserPileRelation extends Model
{
    protected $pk = "id";

    /**
     * 获取信息
     * @param $where
     * @return array|null|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function getInfoByWhere($where){
        return $this->where($where)->order('id','desc')->find();
    }

    //获取用户的充电桩
    function getUserPileList($userId,$page=1,$limit=20){
        $where = ['user_id'=>$userId,'is_delete'=>1,'is_use'=>1,'type'=>1];
        $count = $this->where($where)->count();
        $field = 'id,user_id,relation_id,create_time';
        $getList = $this->where($where)->page($page,$limit)->field($field)->order('create_time','desc')->select();
        if($getList){
            $getList = $getList->toArray();
            $pileModel = new ChargePile();
            $stationModel = new ChargingStation();
            $field = 'id,title,device_sn,station_id,device_type,charge_type,power_number,voltage,electric_current,is_status';
            $statusType = [0=>'否',1=>'是'];
            $deviceType = [1=>'直流',2=>'交流'];
            $chargeType = [1=>'快充',2=>'慢充'];
            foreach ($getList as $key=>$value){
                $pileInfo = $pileModel->getInfoByWhere(['id'=>$value['relation_id']],$field);
                if($pileInfo){
                    $pileInfo['status_name'] = $statusType[$pileInfo['is_status']];
                    $getList[$key]['station_name'] = $stationModel->where('id',$pileInfo['station_id'])->value('title');
                    $pileInfo['device_name'] = isset($deviceType[$pileInfo['device_type']]) ? $deviceType[$pileInfo['device_type']] : '';
                    $pileInfo['charge_name'] = isset($chargeType[$pileInfo['charge_type']]) ? $chargeType[$pileInfo['charge_type']] : '';
                }else{
                    $pileInfo = [];
                }
                $getList[$key]['pile_info'] = $pileInfo;
            }
        }
        return compact("count","getList");
    }



}
